import { Modal,Form, Input, Button, Upload, message,Cascader  } from "antd";
import React, { Component, ReactNode } from "react";
import { instance } from '../../utils/request';
interface EditCategoryProps {
    data: any;
    visible?: boolean;  // 可选属性
    closeModal: () => void;
}

interface Option {
  value: string;
  label: string;
  children?: Option[];
}
class EditCategory extends Component<EditCategoryProps> {

  constructor(props: EditCategoryProps) {
    super(props);
    this.closeModal = this.closeModal.bind(this);
  }

   options: Option[] = [];

   state={
    cat_pid:'',
    cat_id:0,
    cat_name:'',
    cat_level:''
   }
  
  closeModal = () => {
    this.props.closeModal && this.props.closeModal();
  };
  componentDidMount(): void {
    // 重新进行渲染
    // 获取 父级组件传递过来的值
    const {
      cat_id,
      cat_name,
      cat_level,
    } = this.props.data;

    this.setState({cat_name,cat_level,cat_id})
    // 填充表单，获取数据
    this.fromRef.current.setFieldsValue({
      cat_name,
      cat_level,
    });
  }

  onFinish = (values: any) => {
    let params = {
      cat_name: values.cat_name
    };
    instance
      .put(`/categories/${this.state.cat_id}`, params)
      .then((res) => {
        message.success("修改分类完成！");
        this.closeModal()
      })
      .catch((error) => {
        console.log("error=", error);
      });
  };

  onFinishFailed = () => {};

  fromRef = React.createRef<any>();
   onChange = (value: any) => { 
    //选择最后一项
    this.setState({cat_pid:value[value.length - 1]}) ;
  };
  

  render() {
    return (
      <>
      <Modal
      width='800px'
        visible={this.props.visible}
        title="编辑分类"
        cancelText="取消" 
        onCancel={() => this.closeModal()} // 调用父组件的 close 方法
        okButtonProps={{ style: { display: 'none' } }} // Remove the OK button
        destroyOnClose
      >
        <Form
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          ref={this.fromRef}
        >
        <Form.Item
            label="分类名称"
            name="cat_name"
            rules={[{ required: true, message: "请输入分类名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="父级分类"
            name="cat_level"
          >
           <Cascader allowClear options={this.options} onChange={this.onChange} placeholder="请选择分类" />
          </Form.Item>
    
          <Form.Item style={{float:'right',marginLeft:'10px'}}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Modal>
      </>
    );
  }
}

export default EditCategory;
